--author gtrs426
--游戏广播单独起一个服务反正消息拥堵在代理gate_server
local skynet = require"skynet"
local log = require "Log"
local msgpack = require "msgpack_helper"
require "skynet.manager"


local CMD = {}
local run_info = {}
local user_list = {}
local user_agents = {}

function CMD.init(pbc_env)
	msgpack.load(pbc_env)
end

function CMD.user_enter(fd, contype, playerid)
	user_list[playerid] = {fd = fd, contype = contype}
	user_agents[fd] = playerid
end

function CMD.user_out(fd, playerid)
	user_agents[fd] = nil
	user_list[playerid] = nil
end

function CMD.broad_cast(ulist,msgs)
	if not ulist then
		ulist = user_agents
	end
	local user
	if type(msgs) == 'table' and type(ulist) == 'table' then
		for _,playerid in pairs(ulist) do
			user = user_list[playerid]
			if user then 
				for k,v in pairs(msgs) do
					if not msgpack.send_message(user.fd, user.contype, k,v) then
						log.error('send_message faild on handle cmd:',k)
					end
				end
			end
		end
	end
end

function CMD.broadcast(ulist,msgs)
	if not ulist then
		ulist = user_agents
	end
	local user
	if type(msgs) == 'table' and type(ulist) == 'table' then
		for _,playerid in pairs(ulist) do
			user = user_list[playerid]
			if user then 
				for k,v in pairs(msgs) do
					if not msgpack.send_message(user.fd, user.contype, k,v) then
						log.error('send_message faild on handle cmd:',k)
					end
				end
			end
		end
	end
end

function CMD.broadcast_player(tbPlayerMsg)
	if not tbPlayerMsg or type(tbPlayerMsg) ~= 'table' or not next(tbPlayerMsg) then
		return 
	end
	local user	
	for playerid,msg in pairs(tbPlayerMsg) do
		user = user_list[playerid]
		if user and type(msg)=='table' then 
			for k,v in pairs(msg) do
				if not msgpack.send_message(user.fd, user.contype, k,v) then
					log.error('send_message faild on handle cmd:',k)
				end
			end
		end
	end
	
end


skynet.start(function()
	skynet.dispatch("lua", dispatch_command(CMD))
	skynet.register "broadcasting"
end)